<?php

namespace App\Console\Commands\Third\Xiaoke;

use App\Models\Third\Xiaoke\UserModel;
use App\Remote\Guanyuan\GuanyuanRetry\GuanyuanRetryRemote;
use App\Remote\XiaoKe\UserRemote;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Validation\ValidationException;

class UserInitCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'xiaoke:userInit';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '销氪用户初始化';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GuzzleException
     * @throws ValidationException
     */
    public function handle(): int
    {
        $xkMerchantsUser = GuanyuanRetryRemote::sourceData(
            "jf5b1dd66b7f7456397a4e29",
            "ia84ca0cf0976468f8f7f3b4",
            [
                [
                    'name'        => '员工状态',
                    'filterType'  => 'EQ',
                    'filterValue' => ['在职'],
                ]
            ]
        );

        $xkMerchantsUserMobile = array_column($xkMerchantsUser["data"], 9);


        $while    = true;
        $pageSize = 50;
        $pageNum  = 1;
        while ($while) {
            $list           = UserRemote::list($pageNum, $pageSize);
            $listCollection = collect($list["list"] ?? []);
            if ($listCollection->count() > 0) {
                collect($list["list"])->each(function ($v) use ($xkMerchantsUserMobile) {
                    UserModel::query()->updateOrCreate(
                        ["telephone" => $v["telephone"]],
                        [
                            "headImage"   => $v["headImage"],
                            "isAlive"     => $v["isAlive"],
                            "isDel"       => $v["isDel"],
                            "isSeat"      => $v["isSeat"],
                            "zone"        => $v["zone"],
                            "wid"         => $v["wid"],
                            "userName"    => $v["userName"],
                            "userType"    => $v["userType"],
                            "pid"         => $v["pid"],
                            "isMerchants" => in_array($v["telephone"], $xkMerchantsUserMobile)
                        ]
                    );
                });
            }

            if ($listCollection->count() < $pageSize) {
                $while = false;
            } else {
                $pageNum++;
            }

        }
        return 0;
    }
}
